package pos.gengshen.com.gspos.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.printer.UsbThermalPrinter;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import pos.gengshen.com.gspos.R;
import pos.gengshen.com.gspos.common.Constant;
import pos.gengshen.com.gspos.pojo.Order;
import pos.gengshen.com.gspos.pojo.PayRecord;
import pos.gengshen.com.gspos.pojo.Shift;
import pos.gengshen.com.gspos.pojo.ShiftDetail;
import pos.gengshen.com.gspos.utils.DateTimeUtilT;
import pos.gengshen.com.gspos.utils.DisplayUtils;
import pos.gengshen.com.gspos.utils.HttpUtils;
import pos.gengshen.com.gspos.utils.PrintUtils;

/**
 * Created by Administrator on 2018/7/11/011.
 */

public class ShiftActivity extends AppCompatActivity {

    private String url = Constant.SERVER_URL+"/admin/shift/shiftOverAndNew";
    private CheckBox isPrint;
    private Button shift;
    private EditText shifter,workName;
    private TextView tv;
    private ListView listView;
    private TableLayout tableLayout,cardpaycode,exchangGift;
    UsbThermalPrinter mUsbThermalPrinter = new UsbThermalPrinter(ShiftActivity.this);
    List<String> list = new ArrayList<String>();
    Button btn_send;
    String action = "myAction";
    String stringcont;
    ContentPrintThread mThread;
    boolean isStartPrint;
    static boolean printDetail = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_shift);
        isPrint = (CheckBox)findViewById(R.id.isPrint);
        shift = (Button)findViewById(R.id.toshift);
        shifter = (EditText)findViewById(R.id.shifter);
        workName = (EditText)findViewById(R.id.workname);
        //tv = (TextView)findViewById(R.id.shiftDetail);
        tableLayout = (TableLayout) findViewById(R.id.oillist);
        cardpaycode  = (TableLayout)findViewById(R.id.cardpaycode);
        exchangGift = (TableLayout)findViewById(R.id.exchangGift);
        try {
            mUsbThermalPrinter.start(0);
        } catch (TelpoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        IntentFilter pIntentFilter = new IntentFilter();
        pIntentFilter.addAction(action);
        pIntentFilter.addAction("android.intent.action.BATTERY_CAPACITY_EVENT");
        registerReceiver(printReceive, pIntentFilter);


        Intent intent = getIntent();
        //加油记录
        String detail = intent.getStringExtra("shiftDetail");
        JSONObject object = JSON.parseObject(detail);
        JSONObject obj = object.getJSONObject("obj");
        JSONArray oildetail = obj.getJSONArray("detailList");
        String js=oildetail.toJSONString();//toJSONString(oildetail, SerializerFeature.WriteClassName);//将array数组转换成字符串
        final List<ShiftDetail> array =JSONObject.parseArray(js, ShiftDetail.class);
        //交班
        final Shift shift1 = obj.getObject("shift",Shift.class);
        String shopName = obj.getString("shopName");
        shift1.setShopName(shopName);
        //充值记录
        JSONArray recordList = obj.getJSONArray("recordList");
        String rcjs=recordList.toJSONString();
        final List<PayRecord> list = JSONObject.parseArray(rcjs,PayRecord.class);
        //礼品兑换
        JSONArray exchangelist = obj.getJSONArray("orderList");
        String gfjs = exchangelist.toJSONString();
        final List<Order> orderList = JSONObject.parseArray(gfjs,Order.class);
        if(orderList != null){
            for(Order order:orderList){

                TableRow row = new TableRow(ShiftActivity.this);
                row.setGravity(Gravity.CENTER);
                TextView tv1 = new TextView(this);
                if(order.getNick().toCharArray().length >6){
                    tv1.setText(order.getNick().substring(0,5));
                    tv1.append("...");
                }else{
                    tv1.setText(order.getNick());
                }

                tv1.setGravity(Gravity.CENTER);
                tv1.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv1);

                TextView tv2 = new TextView(this);
                tv2.setText(String.valueOf(order.getPayMoney()));
                tv2.setGravity(Gravity.CENTER);
                tv2.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv2);

                TextView tv3 = new TextView(this);
                tv3.setText(DateTimeUtilT.dateTime(order.getExchangeDate()));
                tv3.setGravity(Gravity.CENTER);
                tv3.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv3);
                exchangGift.addView(row,new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));

            }
        }

        if(list != null){
            for(PayRecord pay:list){
                TableRow row = new TableRow(ShiftActivity.this);
                row.setGravity(Gravity.CENTER);
                TextView tv1 = new TextView(this);
                if(pay.getNick().toCharArray().length >6){
                    tv1.setText(pay.getNick().substring(0,4));
                    tv1.append("...");
                }else{
                    tv1.setText(pay.getNick());
                }

                tv1.setGravity(Gravity.CENTER);
                tv1.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv1);

                TextView tv2 = new TextView(this);
                tv2.setText(pay.getCard());
                tv2.setGravity(Gravity.CENTER);
                tv2.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv2);

                TextView tv3 = new TextView(this);
                tv3.setText(String.valueOf(pay.getPayMoney()/100.0));
                tv3.setGravity(Gravity.CENTER);
                tv3.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv3);

                TextView tv4 = new TextView(this);
                if(pay.getIsPay() && pay.getIsRecode()){
                    tv4.setText("充值成功");
                }else if(pay.getIsRecode() && !pay.getIsRecode()){
                    tv4.setText("充值异常");
                }
                tv4.setGravity(Gravity.CENTER);
                tv4.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv4);
                cardpaycode.addView(row,new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));

            }
        }


        final String shiftId = intent.getStringExtra("shiftId");
        if(array != null && array.size()>0){
            for(ShiftDetail detail1 : array){
                System.out.println(detail1);
                TableRow row = new TableRow(ShiftActivity.this);
                row.setGravity(Gravity.CENTER);
                TextView tv1 = new TextView(this);
                tv1.setText(detail1.getId().toString());
                tv1.setGravity(Gravity.CENTER);
                tv1.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv1);

                TextView tv2 = new TextView(this);
                tv2.setText(detail1.getOilCode());
                tv2.setGravity(Gravity.CENTER);
                tv2.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv2);

                TextView tv3 = new TextView(this);
                tv3.setText(String.valueOf(detail1.getPayMoney()/100.0));
                tv3.setGravity(Gravity.CENTER);
                tv3.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv3);

                TextView tv4 = new TextView(this);
                tv4.setText(String.valueOf(detail1.getDiscount()/100.0));
                tv4.setGravity(Gravity.CENTER);
                tv4.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv4);

                TextView tv5 = new TextView(this);
                if(detail1.getState() && !detail1.getRefund()){
                    tv5.setText("支付成功");
                }else if(detail1.getState() && detail1.getRefund()){
                    tv5.setText("退款");
                }
                //tv5.setText(String.valueOf(detail1.getDiscount()/100.0));
                tv5.setGravity(Gravity.CENTER);
                tv5.setHeight(DisplayUtils.dp2px(this,30));
                row.addView(tv5);

                tableLayout.addView(row,new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
            }

        }



        isPrint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(isPrint.isChecked()){
                    printDetail = true;
                    Toast.makeText(ShiftActivity.this,"交班数据打印"+printDetail,Toast.LENGTH_SHORT).show();
                }else{
                    printDetail = false;
                    Toast.makeText(ShiftActivity.this,"交班数据打印"+printDetail,Toast.LENGTH_SHORT).show();
                }


            }
        });


        shift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = workName.getText().toString();
                String worker = shifter.getText().toString();
                if(name.equals("") && worker.equals("")){
                    Toast.makeText(ShiftActivity.this,"情输入交班人和值班名称",Toast.LENGTH_SHORT).show();
                    return;
                }
                printDetail = isPrint.isChecked();
                if(printDetail){
                     stringcont = PrintUtils.getShiftDetailString(shift1,orderList,list,array);
                }else{
                    stringcont = PrintUtils.getShiftDetailString(shift1,null,null,null);
                }

                Map<String,String> map = new HashMap<>();
                map.put("shiftId",shiftId);
                map.put("shopId","1");
                map.put("name",name);
                map.put("worker",worker);
                HttpUtils.doPost(url, null, map, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("请求失败");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ShiftActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println("请求成功");
                        final String result = response.body().string();
                        JSONObject object = JSON.parseObject(result);
                        String code = object.getString("code");
                        if(code.equals("200")){
                            System.out.println("交班成功");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //Toast.makeText(ShiftActivity.this,"交班成功"+stringcont,Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent();
                                    intent.setAction(action);
                                    intent.putExtra("str", stringcont);
                                    sendOrderedBroadcast(intent, null);
                                    ShiftActivity.this.finish();
                                }
                            });
                        }
                    }
                });

            }
        });
    }



    private final BroadcastReceiver printReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String a = intent.getAction();

            if (a.equals(action)) {
                String str = intent.getStringExtra("str");
                list.add(str);
                if (!isStartPrint) {
                    mThread = new ContentPrintThread();
                    mThread.start();
                }

            }
        }
    };




    @Override
    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(printReceive);
        mUsbThermalPrinter.stop();
    }


    private class ContentPrintThread extends Thread {

        @Override
        public void run() {
            super.run();
            try {
                while (list.size() > 0) {
                    isStartPrint = true;
                    mUsbThermalPrinter.reset();
                    mUsbThermalPrinter.setLineSpace(0);
                    mUsbThermalPrinter.setAlgin(UsbThermalPrinter.ALGIN_MIDDLE);
                    mUsbThermalPrinter.setFontSize(1);
                    mUsbThermalPrinter.enlargeFontSize(-1, -1);
                    //mUsbThermalPrinter.addString("欢迎光临");
                    mUsbThermalPrinter.setAlgin(UsbThermalPrinter.ALGIN_LEFT);
                    mUsbThermalPrinter.setFontSize(2);
                    mUsbThermalPrinter.enlargeFontSize(1, 1);
                    mUsbThermalPrinter.addString(list.get(0).toString());
                    //mUsbThermalPrinter.addString("地址：广州市天河区天河北路906高科大厦\n电话：38212803");
                    mUsbThermalPrinter.printString();
                    mUsbThermalPrinter.setAlgin(UsbThermalPrinter.ALGIN_MIDDLE);
                    mUsbThermalPrinter.walkPaper(20);
                    // mUsbThermalPrinter.paperCut();
                    list.remove(0);
                }

            } catch (Exception e) {
                e.printStackTrace();
                // Result = e.toString();
                // if
                // (Result.equals("com.telpo.tps550.api.printer.NoPaperException"))
                // {
                // nopaper = true;
                // } else if
                // (Result.equals("com.telpo.tps550.api.printer.OverHeatException"))
                // {
                // handler.sendMessage(handler.obtainMessage(OVERHEAT, 1, 0,
                // null));
                // } else {
                // handler.sendMessage(handler.obtainMessage(PRINTERR, 1, 0,
                // null));
                // }
            } finally {
                isStartPrint = false;
                // handler.sendMessage(handler.obtainMessage(CANCELPROMPT, 1, 0,
                // null));
                // if (nopaper) {
                // handler.sendMessage(handler.obtainMessage(NOPAPER, 1, 0,
                // null));
                // nopaper = false;
                // return;
                // }
            }
        }
    }




}
